<template>
  <div class="hero-management">
    <!-- 页面标题 -->
    <div class="page-header">
      <h2 class="page-title">英雄管理系统</h2>
      <div class="header-actions">
        <button class="add-hero-btn" @click="showAddHeroModal">
          <span class="btn-icon">+</span>
          添加英雄
        </button>
      </div>
    </div>

    <!-- 搜索和筛选 -->
    <div class="search-section">
      <div class="search-box">
        <input 
          v-model="searchQuery" 
          type="text" 
          placeholder="搜索英雄名称..."
          class="search-input"
          @input="handleSearch"
        />
      </div>
      <div class="filter-box">
        <select v-model="filterType" @change="handleFilter" class="filter-select">
          <option value="">全部类型</option>
          <option value="雷">雷</option>
          <option value="机械">机械</option>
          <option value="生物">生物</option>
          <option value="量子">量子</option>
        </select>
      </div>
    </div>

    <!-- 英雄列表表格 -->
    <div class="table-container" v-if="!loading">
      <table class="hero-table">
        <thead>
          <tr>
            <th>ID</th>
            <th>头像</th>
            <th>英雄名称</th>
            <th>称号</th>
            <th>武器类型</th>
            <th>属性类型</th>
            <th>所属组织</th>
            <th>伤害类型</th>
            <th>创建时间</th>
            <th>操作</th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="hero in paginatedHeroes" :key="hero.id" class="hero-row">
            <td>{{ hero.id }}</td>
            <td>
              <img 
                :src="hero.smallIconUrl || defaultAvatarImage" 
                :alt="hero.heroName"
                class="hero-avatar"
              />
            </td>
            <td class="hero-name-cell">{{ hero.heroName }}</td>
            <td>{{ hero.title }}</td>
            <td>{{ hero.weaponType }}</td>
            <td>
              <span class="attribute-tag" :class="getAttributeClass(hero.attributeType)">
                {{ hero.attributeType }}
              </span>
            </td>
            <td>{{ hero.starRingDivision }}</td>
            <td>{{ hero.damageType }}</td>
            <td>{{ formatDate(hero.createTime) }}</td>
            <td class="action-cell">
              <button class="edit-btn" @click="editHero(hero)" title="编辑">
                ✏️
              </button>
              <button class="delete-btn" @click="deleteHero(hero)" title="删除">
                🗑️
              </button>
            </td>
          </tr>
        </tbody>
      </table>
    </div>

    <!-- 分页 -->
    <div class="pagination" v-if="totalPages > 1">
      <button 
        class="page-btn" 
        :disabled="currentPage === 1" 
        @click="changePage(currentPage - 1)"
      >
        上一页
      </button>
      <span class="page-info">
        第 {{ currentPage }} 页，共 {{ totalPages }} 页
      </span>
      <button 
        class="page-btn" 
        :disabled="currentPage === totalPages" 
        @click="changePage(currentPage + 1)"
      >
        下一页
      </button>
    </div>

    <!-- 加载状态 -->
    <div v-if="loading" class="loading-container">
      <div class="loading-spinner"></div>
      <p>加载中...</p>
    </div>

    <!-- 错误状态 -->
    <div v-if="error" class="error-container">
      <p>{{ error }}</p>
      <button @click="loadHeroes" class="retry-btn">重试</button>
    </div>

    <!-- 添加/编辑英雄模态框 -->
    <div v-if="showAddModal || showEditModal" class="modal-overlay" @click="closeModal">
      <div class="modal-content" @click.stop>
        <div class="modal-header">
          <h3>{{ showAddModal ? '添加英雄' : '编辑英雄' }}</h3>
          <button class="close-btn" @click="closeModal">×</button>
        </div>
        <div class="modal-body">
          <form @submit.prevent="submitForm">
            <div class="form-group">
              <label>英雄名称</label>
              <input v-model="formData.heroName" type="text" required class="form-input" />
            </div>
            <div class="form-group">
              <label>称号</label>
              <input v-model="formData.title" type="text" required class="form-input" />
            </div>
            <div class="form-group">
              <label>武器类型</label>
              <select v-model="formData.weaponType" required class="form-select">
                <option value="">请选择</option>
                <option value="太刀">太刀</option>
                <option value="双枪">双枪</option>
                <option value="重炮">重炮</option>
                <option value="拳套">拳套</option>
                <option value="十字架">十字架</option>
                <option value="镰刀">镰刀</option>
              </select>
            </div>
            <div class="form-group">
              <label>属性类型</label>
              <select v-model="formData.attributeType" required class="form-select">
                <option value="">请选择</option>
                <option value="雷">雷</option>
                <option value="机械">机械</option>
                <option value="生物">生物</option>
                <option value="量子">量子</option>
                <option value="虚数">虚数</option>
              </select>
            </div>
            <div class="form-group">
              <label>所属组织</label>
              <input v-model="formData.starRingDivision" type="text" required class="form-input" />
            </div>
            <div class="form-group">
              <label>伤害类型</label>
              <input v-model="formData.damageType" type="text" required class="form-input" />
            </div>
            <div class="form-group">
              <label>背景描述</label>
              <textarea v-model="formData.backgroundDescription" rows="4" class="form-textarea"></textarea>
            </div>
            <div class="form-group">
              <label>小图标URL</label>
              <input v-model="formData.smallIconUrl" type="url" class="form-input" />
            </div>
            <div class="form-group">
              <label>大图标URL</label>
              <input v-model="formData.largeIconUrl" type="url" class="form-input" />
            </div>
            <div class="form-group">
              <label>视频URL</label>
              <input v-model="formData.videoUrl" type="url" class="form-input" />
            </div>
            <div class="form-actions">
              <button type="button" class="cancel-btn" @click="closeModal">取消</button>
              <button type="submit" class="submit-btn" :disabled="submitting">
                {{ submitting ? '提交中...' : (showAddModal ? '添加' : '更新') }}
              </button>
            </div>
          </form>
        </div>
      </div>
    </div>

    <!-- 删除确认模态框 -->
    <div v-if="showDeleteModal" class="modal-overlay" @click="closeDeleteModal">
      <div class="modal-content delete-modal" @click.stop>
        <div class="modal-header">
          <h3>确认删除</h3>
          <button class="close-btn" @click="closeDeleteModal">×</button>
        </div>
        <div class="modal-body">
          <p>确定要删除英雄 <strong>{{ heroToDelete?.heroName }}</strong> 吗？</p>
          <p class="warning-text">此操作不可撤销！</p>
          <div class="form-actions">
            <button type="button" class="cancel-btn" @click="closeDeleteModal">取消</button>
            <button type="button" class="delete-confirm-btn" @click="confirmDelete" :disabled="deleting">
              {{ deleting ? '删除中...' : '确认删除' }}
            </button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { heroApi } from '../api/hero.js'

export default {
  name: 'HeroManagement',
  data() {
    return {
      heroes: [],
      filteredHeroes: [],
      loading: true,
      error: null,
      searchQuery: '',
      filterType: '',
      currentPage: 1,
      pageSize: 10,
      
      // 模态框状态
      showAddModal: false,
      showEditModal: false,
      showDeleteModal: false,
      
      // 表单数据
      formData: {
        heroName: '',
        title: '',
        weaponType: '',
        attributeType: '',
        starRingDivision: '',
        damageType: '',
        backgroundDescription: '',
        smallIconUrl: '',
        largeIconUrl: '',
        videoUrl: ''
      },
      
      // 编辑和删除相关
      editingHero: null,
      heroToDelete: null,
      submitting: false,
      deleting: false,
      
      defaultAvatarImage: 'https://fastcdn.mihoyo.com/content-v2/bh3/156251/ea55b240730debec811239cbb393a7bb_2296978660569028145.png'
    }
  },
  computed: {
    paginatedHeroes() {
      const start = (this.currentPage - 1) * this.pageSize
      const end = start + this.pageSize
      return this.filteredHeroes.slice(start, end)
    },
    totalPages() {
      return Math.ceil(this.filteredHeroes.length / this.pageSize)
    }
  },
  mounted() {
    this.loadHeroes()
  },
  methods: {
    async loadHeroes() {
      try {
        this.loading = true
        this.error = null
        
        const response = await heroApi.getAllHeroes()
        if (response.code === 0) {
          this.heroes = response.data || []
          this.filteredHeroes = [...this.heroes]
        } else {
          this.error = response.message || '获取英雄数据失败'
        }
      } catch (err) {
        console.error('加载英雄数据失败:', err)
        this.error = '网络错误，请稍后重试'
      } finally {
        this.loading = false
      }
    },
    
    handleSearch() {
      this.filterHeroes()
    },
    
    handleFilter() {
      this.filterHeroes()
    },
    
    filterHeroes() {
      let filtered = [...this.heroes]
      
      // 按名称搜索
      if (this.searchQuery.trim()) {
        const query = this.searchQuery.toLowerCase()
        filtered = filtered.filter(hero => 
          hero.heroName.toLowerCase().includes(query) ||
          hero.title.toLowerCase().includes(query)
        )
      }
      
      // 按类型筛选
      if (this.filterType) {
        filtered = filtered.filter(hero => hero.attributeType === this.filterType)
      }
      
      this.filteredHeroes = filtered
      this.currentPage = 1 // 重置到第一页
    },
    
    changePage(page) {
      if (page >= 1 && page <= this.totalPages) {
        this.currentPage = page
      }
    },
    
    // 模态框操作
    showAddHeroModal() {
      // 这里可以添加显示添加英雄模态框的逻辑
      console.log('点击了添加英雄按钮')
      // 暂时只是一个占位方法，实际功能可以后续实现
    },
    
    closeModal() {
      this.showAddModal = false
      this.showEditModal = false
      this.resetForm()
    },
    
    closeDeleteModal() {
      this.showDeleteModal = false
      this.heroToDelete = null
    },
    
    resetForm() {
      this.formData = {
        heroName: '',
        title: '',
        weaponType: '',
        attributeType: '',
        starRingDivision: '',
        damageType: '',
        backgroundDescription: '',
        smallIconUrl: '',
        largeIconUrl: '',
        videoUrl: ''
      }
      this.editingHero = null
    },
    
    // 编辑英雄
    editHero(hero) {
      this.editingHero = hero
      this.formData = { ...hero }
      this.showEditModal = true
    },
    
    // 删除英雄
    deleteHero(hero) {
      this.heroToDelete = hero
      this.showDeleteModal = true
    },
    
    async confirmDelete() {
      if (!this.heroToDelete) return
      
      try {
        this.deleting = true
        const response = await heroApi.deleteHero(this.heroToDelete.id)
        
        if (response.code === 0) {
          this.$message?.success('删除成功')
          this.loadHeroes() // 重新加载数据
          this.closeDeleteModal()
        } else {
          this.$message?.error(response.message || '删除失败')
        }
      } catch (err) {
        console.error('删除英雄失败:', err)
        this.$message?.error('删除失败，请稍后重试')
      } finally {
        this.deleting = false
      }
    },
    
    // 提交表单
    async submitForm() {
      try {
        this.submitting = true
        let response
        
        if (this.showAddModal) {
          response = await heroApi.addHero(this.formData)
        } else {
          response = await heroApi.updateHero({ ...this.formData, id: this.editingHero.id })
        }
        
        if (response.code === 0) {
          this.$message?.success(this.showAddModal ? '添加成功' : '更新成功')
          this.loadHeroes() // 重新加载数据
          this.closeModal()
        } else {
          this.$message?.error(response.message || '操作失败')
        }
      } catch (err) {
        console.error('提交表单失败:', err)
        this.$message?.error('操作失败，请稍后重试')
      } finally {
        this.submitting = false
      }
    },
    
    // 工具方法
    formatDate(dateString) {
      if (!dateString) return '-'
      return new Date(dateString).toLocaleDateString('zh-CN')
    },
    
    getAttributeClass(attributeType) {
      const classMap = {
        '雷': 'thunder',
        '机械': 'mech',
        '生物': 'bio',
        '量子': 'quantum',
        '虚数': 'imaginary'
      }
      return classMap[attributeType] || 'default'
    },
    
    // 强制刷新数据
    async forceRefresh() {
      await this.loadHeroes()
      this.$message?.success('数据已刷新')
    }
  }
}
</script>

<style scoped>
.hero-management {
  padding: 20px;
  background: linear-gradient(135deg, #1a1a2e 0%, #16213e 50%, #0f3460 100%);
  min-height: 100vh;
  color: white;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 30px;
}

.page-title {
  font-size: 2.5rem;
  font-weight: bold;
  margin: 0;
  background: linear-gradient(45deg, #ff6b6b, #4ecdc4);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  background-clip: text;
}

.header-actions {
  display: flex;
  gap: 12px;
  align-items: center;
}

.add-hero-btn {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 12px 24px;
  background: linear-gradient(45deg, #ff6b6b, #4ecdc4);
  color: white;
  border: none;
  border-radius: 8px;
  cursor: pointer;
  font-size: 1rem;
  font-weight: 600;
  transition: all 0.3s ease;
  box-shadow: 0 2px 8px rgba(255, 107, 107, 0.3);
}

.add-hero-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 15px rgba(255, 107, 107, 0.4);
}

.add-hero-btn .btn-icon {
  font-size: 1.2rem;
  font-weight: bold;
}

.refresh-btn {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 10px 20px;
  background: linear-gradient(45deg, #4ecdc4, #44a08d);
  color: white;
  border: none;
  border-radius: 8px;
  cursor: pointer;
  font-size: 0.9rem;
  font-weight: 500;
  transition: all 0.3s ease;
}

.refresh-btn:hover:not(:disabled) {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(78, 205, 196, 0.4);
}

.refresh-btn:disabled {
  opacity: 0.6;
  cursor: not-allowed;
  transform: none;
}

.refresh-icon {
  font-size: 14px;
  animation: none;
}

.refresh-btn:not(:disabled):hover .refresh-icon {
  animation: rotate 1s linear infinite;
}

@keyframes rotate {
  from { transform: rotate(0deg); }
  to { transform: rotate(360deg); }
}

.add-btn {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 12px 24px;
  background: linear-gradient(45deg, #ff6b6b, #4ecdc4);
  color: white;
  border: none;
  border-radius: 8px;
  cursor: pointer;
  font-size: 1rem;
  font-weight: 500;
  transition: all 0.3s ease;
}

.add-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 5px 15px rgba(255, 107, 107, 0.4);
}

.add-icon {
  font-size: 1.2rem;
  font-weight: bold;
}

.search-section {
  display: flex;
  gap: 20px;
  margin-bottom: 30px;
  align-items: center;
}

.search-box {
  flex: 1;
}

.search-input {
  width: 100%;
  padding: 12px 16px;
  border: 1px solid rgba(255, 255, 255, 0.2);
  border-radius: 8px;
  background: rgba(255, 255, 255, 0.1);
  color: white;
  font-size: 1rem;
}

.search-input::placeholder {
  color: rgba(255, 255, 255, 0.6);
}

.filter-select {
  padding: 12px 16px;
  border: 1px solid rgba(255, 255, 255, 0.2);
  border-radius: 8px;
  background: rgba(255, 255, 255, 0.1);
  color: white;
  font-size: 1rem;
  min-width: 150px;
}

.filter-select option {
  background: rgba(20, 20, 20, 0.9);
  color: #fff;
}

.table-container {
  background: rgba(255, 255, 255, 0.05);
  border-radius: 12px;
  overflow: hidden;
  margin-bottom: 30px;
}

.hero-table {
  width: 100%;
  border-collapse: collapse;
}

.hero-table th {
  background: rgba(255, 255, 255, 0.1);
  padding: 15px 12px;
  text-align: left;
  font-weight: 600;
  border-bottom: 1px solid rgba(255, 255, 255, 0.1);
}

.hero-table td {
  padding: 12px;
  border-bottom: 1px solid rgba(255, 255, 255, 0.05);
}

.hero-row:hover {
  background: rgba(255, 255, 255, 0.05);
}

.hero-avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  object-fit: cover;
}

.hero-name-cell {
  font-weight: 600;
  color: #4ecdc4;
}

.attribute-tag {
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 0.8rem;
  font-weight: 500;
}

.attribute-tag.thunder { background: #9c27b0; }
.attribute-tag.mech { background: #ff9800; }
.attribute-tag.bio { background: #4caf50; }
.attribute-tag.quantum { background: #2196f3; }
.attribute-tag.imaginary { background: #e91e63; }
.attribute-tag.default { background: #757575; }

.action-cell {
  display: flex;
  gap: 8px;
}

.edit-btn, .delete-btn {
  padding: 6px 10px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 0.9rem;
  transition: all 0.3s ease;
}

.edit-btn {
  background: #4ecdc4;
  color: white;
}

.edit-btn:hover {
  background: #45b7aa;
}

.delete-btn {
  background: #ff6b6b;
  color: white;
}

.delete-btn:hover {
  background: #ff5252;
}

.pagination {
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 20px;
  margin-top: 30px;
}

.page-btn {
  padding: 10px 20px;
  background: rgba(255, 255, 255, 0.1);
  color: white;
  border: 1px solid rgba(255, 255, 255, 0.2);
  border-radius: 6px;
  cursor: pointer;
  transition: all 0.3s ease;
}

.page-btn:hover:not(:disabled) {
  background: rgba(255, 255, 255, 0.2);
}

.page-btn:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.page-info {
  color: #b0b0b0;
}

/* 模态框样式 */
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.7);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}

.modal-content {
  background: #1a1a2e;
  border-radius: 12px;
  width: 90%;
  max-width: 600px;
  max-height: 90vh;
  overflow-y: auto;
  border: 1px solid rgba(255, 255, 255, 0.1);
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px;
  border-bottom: 1px solid rgba(255, 255, 255, 0.1);
}

.modal-header h3 {
  margin: 0;
  color: #4ecdc4;
}

.close-btn {
  background: none;
  border: none;
  color: white;
  font-size: 1.5rem;
  cursor: pointer;
  padding: 0;
  width: 30px;
  height: 30px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.modal-body {
  padding: 20px;
}

.form-group {
  margin-bottom: 20px;
}

.form-group label {
  display: block;
  margin-bottom: 8px;
  color: #b0b0b0;
  font-weight: 500;
}

.form-input, .form-select, .form-textarea {
  width: 100%;
  padding: 12px;
  border: 1px solid rgba(255, 255, 255, 0.2);
  border-radius: 6px;
  background: rgba(255, 255, 255, 0.1);
  color: white;
  font-size: 1rem;
}

.form-select option {
  background: rgba(20, 20, 20, 0.9);
  color: #fff;
}

.form-textarea {
  resize: vertical;
  min-height: 80px;
}

.form-actions {
  display: flex;
  gap: 12px;
  justify-content: flex-end;
  margin-top: 30px;
}

.cancel-btn, .submit-btn, .delete-confirm-btn {
  padding: 12px 24px;
  border: none;
  border-radius: 6px;
  cursor: pointer;
  font-size: 1rem;
  font-weight: 500;
  transition: all 0.3s ease;
}

.cancel-btn {
  background: rgba(255, 255, 255, 0.1);
  color: white;
}

.cancel-btn:hover {
  background: rgba(255, 255, 255, 0.2);
}

.submit-btn {
  background: linear-gradient(45deg, #ff6b6b, #4ecdc4);
  color: white;
}

.submit-btn:hover:not(:disabled) {
  transform: translateY(-1px);
  box-shadow: 0 3px 10px rgba(255, 107, 107, 0.3);
}

.submit-btn:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}

.delete-confirm-btn {
  background: #ff6b6b;
  color: white;
}

.delete-confirm-btn:hover:not(:disabled) {
  background: #ff5252;
}

.delete-modal {
  max-width: 400px;
}

.warning-text {
  color: #ff6b6b;
  font-size: 0.9rem;
  margin-top: 10px;
}

.loading-container,
.error-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  min-height: 400px;
  text-align: center;
}

.loading-spinner {
  width: 50px;
  height: 50px;
  border: 4px solid rgba(255, 255, 255, 0.3);
  border-top: 4px solid #ff6b6b;
  border-radius: 50%;
  animation: spin 1s linear infinite;
  margin-bottom: 20px;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

.retry-btn {
  padding: 10px 20px;
  background: #ff6b6b;
  color: white;
  border: none;
  border-radius: 5px;
  cursor: pointer;
  margin-top: 10px;
  transition: background 0.3s ease;
}

.retry-btn:hover {
  background: #ff5252;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .hero-management {
    padding: 10px;
  }
  
  .page-header {
    flex-direction: column;
    gap: 20px;
    text-align: center;
  }
  
  .search-section {
    flex-direction: column;
  }
  
  .hero-table {
    font-size: 0.9rem;
  }
  
  .hero-table th,
  .hero-table td {
    padding: 8px 6px;
  }
  
  .modal-content {
    width: 95%;
    margin: 10px;
  }
}
</style>